/**
 * @description: 朝云
 * @author: jackZ(465299747@QQ.COM)
 */
import store from "./factory"
let loginModal = false;

export const isDev = true; // true => 测试环境 | false => 正式环境,设置为true
const baseUrl = isDev ? "https://cy.api.nbkjsb.com:9005/" : "https://cy.api.nbkjsb.com:9005/";
export const config = {
    appid: "wx9df262639b29aebb",
    appVersion: '1.0.0'
}

const request = (url, method, data = {}, type = 1) => {
    const deviceId = store.get("openid");
    const token = store.get("token") ? store.get("token") : ""
    let DefaultHeader = {
        'content-type': 'application/json',
        'osVersion': "weixin",
        'appVersion': config.appVersion,
        'appName': 'qx_miniProgram',
        'deviceId': deviceId
    }
    if (token) {
        DefaultHeader.Authorization = `${token}`
    }
    // 获取当前位置后请求操作
    return new Promise((resolve, reject) => {
        wx.request({
            url: `${baseUrl}${url}`,
            data: data,
            method: method.toUpperCase(),
            header: DefaultHeader,
            success(res) {
                const statusCode = res.statusCode;
                if (statusCode === 200) {
                    resolve(res.data);
                } else {
                    if (statusCode === 401) {
                        wx.hideLoading();
                        if (loginModal == false) {
                            lostLoginWarn();
                        }
                        reject(res);
                    } else {
                        if (statusCode >= 500) {
                            wx.showToast({
                                title: '服务器异常', //提示的内容,
                                icon: 'none', //图标,
                            });
                        }
                        wx.hideLoading();
                        reject(res);
                    }
                }
            },
            fail(err) {
                wx.hideLoading();
                reject(err);
            }
        })
    });

}

function lostLoginWarn() {
    loginModal = true
    //移动登录信息,实名认证信息,注册路由,免押信息
    store.clear()
    wx.showModal({
        title: "温馨提示",
        content: '登录丢失, 请重新登录',
        confirmText: '登录',
        showCancel: false,
        success(res) {
            loginModal = false
            // 点 `登录` 跳转到登录页面
            if (res.confirm) {
                wx.navigateTo({
                    url: '../autoLogin/autoLogin'
                });
            }
        }
    });
    return false
}

/**
 * [get | post | patch 请求方式]
 * @param {String} url [必填, 请求地址]
 * @param {Object} data [选填, 请求参数]
 * @return Promise
 */
const get = (url, data) => {
    return request(url, 'GET', data);
}

const post = (url, data) => {
    return request(url, 'POST', data);
}

const put = (url, data) => {
    return request(url, 'PUT', data);
}

// 导出定义接口
export const WX = {
    request,
    get,
    post,
    put
};